package me.sdau.spider.manager.modules.system.service.impl;

import com.google.common.collect.Lists;
import me.sdau.spider.manager.common.entity.bo.Tree;
import me.sdau.spider.manager.modules.system.entity.Menu;
import me.sdau.spider.manager.modules.system.mapper.MenuMapper;
import me.sdau.spider.manager.modules.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author zj
 * @date 2018/4/9 14:53
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public Menu getMenuById(Long id) {
        return menuMapper.getOne(id);
    }

    @Override
    public int insertMenu(Menu menu) {
        return menuMapper.insert(menu);
    }

    @Override
    public List<Tree<Menu>> listMuneTree(Long id) {
        List<Menu> menus = menuMapper.listMenuByUserId(id)
                .stream()
                .filter(menu -> Objects.equals(menu.getType(), 0) || Objects.equals(menu.getType(), 1))
                .collect(Collectors.toList());

        List<Tree<Menu>> memuTrees = Lists.newArrayList();

        menus.forEach(menu -> memuTrees.add(Tree.<Menu>builder()
                .id(menu.getId())
                .parentId(menu.getParentId())
                .text(menu.getName())
                .href(menu.getHref())
                .icon(menu.getIcon())
                .children(Lists.newArrayList())
                .build()));

        List<Tree<Menu>> treeList = memuTrees.stream()
                .filter(tree -> Objects.equals(tree.getParentId(), 0L))
                .collect(Collectors.toList());

        treeList.forEach(tree -> memuTrees.stream()
                .filter(menu -> Objects
                        .equals(menu.getParentId(), tree.getId()))
                .forEach(menu -> tree
                        .getChildren()
                            .add(menu)));
        return treeList;
    }

    @Override
    public List<Menu> list() {
        return menuMapper.findAll();
    }
}
